package com.youchuang.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import com.youchuang.bean.Category;
import com.youchuang.common.HibernateConnection;
import com.youchuang.dao.CategoryDAO;

@Repository("categoryDAO")
public class CategoryDAOImpl implements CategoryDAO {

	private static final String HQL_FIND_BY_PARENT_ID = "from Category where parentId = :parentId";
	private static final String HQL_FIND_BY_ID = "from Category where id = :id";
	private static final String HQL_FIND_ALL = "from Category";

	@Resource
	private HibernateConnection<Category> hibernateConnection;

	@Override
	public void save(Category t) {
		//Do nothing because of it unusual
	}

	@Override
	public void delete(Category t) {
		hibernateConnection.delete(t);
	}

	@Override
	public int update(Category t) {
		hibernateConnection.update(t);
		return 1;
	}

	@Override
	public List<Category> queryAll() {
		return hibernateConnection.find(HQL_FIND_ALL);
	}

	@Override
	public List<Category> queryByParentId(String parentId) {
		Map<String, Object> params = new HashMap<>();
		params.put("parentId", parentId);
		return hibernateConnection.find(HQL_FIND_BY_PARENT_ID, params);
	}

	@Override
	public Category queryById(String id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		List<Category> list = hibernateConnection.find(HQL_FIND_BY_ID, params);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public void saveOrUpdate(Category category) {
		hibernateConnection.saveOrUpdate(category);
	}

}
